package cn.xw.DLXQueue;

import cn.xw.utils.ChannelUtil;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author AnHui OuYang
 * @version 1.0
 * created at 2023-04-11 22:14
 * 死信消费者（用来处理死信队列数据）
 */
public class DLXConsumer {

    //通过日志管理器获取Logger对象
    static Logger logger = LogManager.getLogger(Producer.class);
    //声明死信交换机名称
    public static final String DLX_EXCHANGE = "DLXExchange";
    //声明死信队列名称
    public static final String DLX_QUEUE = "DLXQueue";
    //声明路由绑定关系 Routing Key 死信交换机到死信队列
    public static final String DLX_KEY = "DLXKey";

    /***
     * 死信消费者
     */
    public static void main(String[] args) throws IOException {
        //通过工具类获取一个信道
        Channel channel = ChannelUtil.getChannel();
        //创建死信交换机(此时死信交换机为直接交换机（路由模式）直接路由到指定队列)
        channel.exchangeDeclare(DLX_EXCHANGE, BuiltinExchangeType.DIRECT, true, false, null);
        //创建死信队列(并设置持久化的队列)
        channel.queueDeclare(DLX_QUEUE, true, false, false, null);
        //把死信队列绑定到死信交换机上
        channel.queueBind(DLX_QUEUE, DLX_EXCHANGE, DLX_KEY);
        logger.info("死信队列开始监听队列消息....");
        //接收消息
        channel.basicConsume(DLX_QUEUE, true, (consumerTag, message) -> {
            logger.info("死信队列接收并处理本次消息：{}", new String(message.getBody(), StandardCharsets.UTF_8));
        }, (consumerTag) -> {
            logger.info("监听的死信队列出现异常；可能队列被删除！{}", consumerTag);
        });
    }
}